package com.chushouya.order.service.admin.impl;

import com.chushouya.order.constants.OrderActionEnum;
import com.chushouya.order.dao.repository.*;
import com.chushouya.order.service.common.impl.OrderLogServiceImpl;
import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.service.common.CommonProductService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.chushouya.order.constants.BizTypeEnum;
import com.chushouya.order.constants.OrderListLogicStatusEnum;
import com.chushouya.order.constants.OrderTypeEnum;
import com.chushouya.order.dao.entity.OrderAddressEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.entity.OrderProductEntity;
//=====order.dao.repository.*;
import com.chushouya.order.dao.repository.*;
import com.chushouya.order.dto.admin.order.OrderDataDTO;
import com.chushouya.order.dto.admin.order.OrderListDTO;
import com.chushouya.order.dto.admin.order.OrderLogicStatus;
import com.chushouya.order.dto.admin.order.OrderQuery;
import com.chushouya.order.dto.admin.order.UpdateOrderProductDTO;
import com.chushouya.order.dto.admin.orderaddress.OrderAddressDTO;
import com.chushouya.order.dto.admin.orderextend.OrderExtendDTO;
import com.chushouya.order.dto.admin.orderproduct.OrderProductDTO;
import com.chushouya.order.service.admin.AdminOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AdminOrderServiceImpl implements AdminOrderService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderAddressRepository orderAddressRepository;

    @Resource
    private OrderProductRepository orderProductRepository;

    @Resource
    private CommonProductService commonProductService;

    @Resource
    private OrderExtendRepository orderExtendRepository;
    @Autowired
    private OrderLogServiceImpl orderLogServiceImpl;

    @Override
    public PageResult<OrderListDTO> selectOrderList(OrderQuery query) {
        OrderQuery orderQuery = handleOrderQuery(query);
        return PageResult.of(orderRepository.selectPageResult(orderQuery), OrderListDTO.class);
    }

    @Override
    public OrderDataDTO selectOrderDetail(Long orderId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        OrderDataDTO orderDataDTO = Beans.copy(orderEntity, OrderDataDTO.class);

        orderDataDTO.setOrderAddress(Beans.copy(this.orderAddressInfo(orderId), OrderAddressDTO.class));
        orderDataDTO.setOrderProduct(this.orderEvaluateProduct(orderId));
        orderDataDTO.setOrderExtend(Beans.copy(this.orderExtendInfo(orderId), OrderExtendDTO.class));
        orderDataDTO.setOrderRemark(Strings.defaultString(orderEntity.getOrderRemark(), ""));
        return orderDataDTO;
    }

    @Override
    public List<OrderLogicStatus> selectStatusCount(OrderQuery query) {
        return Collections.emptyList();
    }

    @Override
    public OrderDataDTO selectPartnerOrderDetail(Long orderId, Long partnerId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        if (!Objects.equals(orderEntity.getPartnerId(), partnerId)) {
            throw Ex.business("订单不属于该合作商");
        }
        OrderDataDTO orderDataDTO = Beans.copy(orderEntity, OrderDataDTO.class);

        orderDataDTO.setOrderAddress(Beans.copy(this.orderAddressInfo(orderId), OrderAddressDTO.class));
        orderDataDTO.setOrderProduct(this.orderEvaluateProduct(orderId));
        orderDataDTO.setOrderExtend(Beans.copy(this.orderExtendInfo(orderId), OrderExtendDTO.class));
        orderDataDTO.setOrderRemark(Strings.defaultString(orderEntity.getOrderRemark(), ""));
        return orderDataDTO;
    }

    @Override
    public void updateOrderProduct(Long orderId, Long productId) {
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        ProductEntity productEntity = commonProductService.getProductInfo(productId);
        OrderEntity updateOrder = new OrderEntity();
        updateOrder.setOrderId(orderId);
        updateOrder.setProductId(productId);
        updateOrder.setProductName(productEntity.getProductName());
        updateOrder.setProductImage(productEntity.getProductImage());
        orderRepository.updateByPrimaryKeySelective(updateOrder);

        OrderProductEntity orderProductEntity = orderProductRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderProductEntity)) {
            throw Ex.business("订单商品信息不存在");
        }
        OrderProductEntity updateOrderProduct = new OrderProductEntity();
        updateOrderProduct.setOrderProductId(orderProductEntity.getOrderProductId());
        updateOrderProduct.setProductId(productId);
        updateOrderProduct.setOriginalProductName(productEntity.getProductName());
        updateOrderProduct.setProductName(productEntity.getProductName());
        updateOrderProduct.setProductImage(productEntity.getProductImage());
        orderProductRepository.updateByPrimaryKeySelective(updateOrderProduct);

        final String msg = Strings.format("修改机型，原机型：{}，修改后的机型：{}", orderEntity.getProductName(), productEntity.getProductName());
        orderLogServiceImpl.addOrderActionLog(orderId, OrderActionEnum.FOLLOW_ORDER.value(), msg);
    }

    @Override
    public void updateOrderProduct(UpdateOrderProductDTO updateOrderProductDTO) {
        if (updateOrderProductDTO == null) {
            throw Ex.business("更新订单产品信息参数不能为空");
        }
        
        Long orderId = updateOrderProductDTO.getOrderId();
        Long productId = updateOrderProductDTO.getProductId();
        
        // 验证订单是否存在
        OrderEntity orderEntity = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(orderEntity)) {
            throw Ex.business("订单不存在");
        }
        
        // 获取产品信息
        ProductEntity productEntity = commonProductService.getProductInfo(productId);
        if (Objects.isNull(productEntity)) {
            throw Ex.business("产品不存在");
        }
        
        // 更新订单表中的产品信息
        OrderEntity updateOrder = new OrderEntity();
        updateOrder.setOrderId(orderId);
        updateOrder.setProductId(productId);
        
        // 优先使用DTO中的产品名称和图片，如果为空则使用产品实体中的信息
        String productName = Strings.isNotBlank(updateOrderProductDTO.getProductName()) 
            ? updateOrderProductDTO.getProductName() 
            : productEntity.getProductName();
        String productImage = Strings.isNotBlank(updateOrderProductDTO.getProductImage()) 
            ? updateOrderProductDTO.getProductImage() 
            : productEntity.getProductImage();
            
        updateOrder.setProductName(productName);
        updateOrder.setProductImage(productImage);
        orderRepository.updateByPrimaryKeySelective(updateOrder);

        // 更新订单产品表中的信息
        OrderProductEntity orderProductEntity = orderProductRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderProductEntity)) {
            throw Ex.business("订单商品信息不存在");
        }
        
        OrderProductEntity updateOrderProduct = new OrderProductEntity();
        updateOrderProduct.setOrderProductId(orderProductEntity.getOrderProductId());
        updateOrderProduct.setProductId(productId);
        updateOrderProduct.setProductName(productName);
        updateOrderProduct.setProductImage(productImage);
        orderProductRepository.updateByPrimaryKeySelective(updateOrderProduct);

        // 记录操作日志
        final String msg = Strings.format("更新订单产品信息，原产品：{}，新产品：{}", 
            orderEntity.getProductName(), productName);
        orderLogServiceImpl.addOrderActionLog(orderId, OrderActionEnum.FOLLOW_ORDER.value(), msg);
        
        log.info("更新订单产品信息成功，订单ID：{}，产品ID：{}，产品名称：{}", orderId, productId, productName);
    }

    /**
     * 公共搜索函数
     */
    private OrderQuery handleOrderQuery(OrderQuery query) {
        if (Objects.nonNull(query.getLogicStatus())) {
            query.setOrderStatusList(OrderListLogicStatusEnum.get(query.getLogicStatus()).statusList());
            if (query.getLogicStatus().equals(OrderListLogicStatusEnum.expressConfirm.value())) {
                query.setOrderType(OrderTypeEnum.EXPRESS_RECYCLE.value());
            } else if (query.getLogicStatus().equals(OrderListLogicStatusEnum.visitConfirm.value())) {
                query.setOrderType(OrderTypeEnum.DOOR_RECYCLE.value());
            }
        }
        query.setBizType(BizTypeEnum.SHUMA.value());
        return query;
    }

    /**
     * 获取订单用户收货地址信息
     */
    private OrderAddressEntity orderAddressInfo(Long orderId) {
        OrderAddressEntity orderAddress = orderAddressRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderAddress)) {
            throw Ex.business("订单收货地址不存在");
        }
        return orderAddress;
    }

    /**
     * 获取订单商品信息
     */
    private OrderProductDTO orderEvaluateProduct(Long orderId) {
        OrderProductEntity orderProductEntity = orderProductRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderProductEntity)) {
            throw Ex.business("订单商品信息不存在");
        }
        OrderProductDTO orderProductDTO = Beans.copy(orderProductEntity, OrderProductDTO.class);
        orderProductDTO.setEvaluateItem(Jsons.parseArray(orderProductEntity.getEvaluateItem(), Object.class));
        orderProductDTO.setQualityItem(Jsons.parseArray(orderProductEntity.getQualityItem(), Object.class));
        return orderProductDTO;
    }

    /**
     * 获取订单额外信息
     */
    private OrderExtendEntity orderExtendInfo(Long orderId) {
        OrderExtendEntity orderExtend = orderExtendRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderExtend)) {
            throw Ex.business("订单额外信息不存在");
        }
        return orderExtend;
    }
}
